package com.cswnode.Service.impl;

import com.cswnode.Dao.UserMapper;
import com.cswnode.Entity.User;
import com.cswnode.Service.RegisteredService;
import com.cswnode.Util.CommunityUtil;
import com.cswnode.Util.Constant;
import com.cswnode.Util.MailClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class RegisteredServiceImpl implements RegisteredService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private MailClient mailClient;
    @Value("${community.path.domain}")
    private String domain;
    @Value("${server.servlet.context-path}")
    private String contextpath;

    /**
     *
     * @param username
     * @return true:该用户存在；false：该用户不存在
     */
    public int JudgeUsername(String username){
        return userMapper.JudgeByName(username);
    }

    /**
     *
     * @param email
     * @return true:该用户存在；false：该用户不存在
     */
    @Override
    public Boolean JudgeEmail(String email) {
        int i = userMapper.JudgeByEmail(email);
        if (i == 0){
            return false;
        }
        return true;
    }

    @Override
    public Map<String,Object> RegisterdUser(User user) {
        Map<String,Object> map = new HashMap<>();
        if (user == null){
            throw new IllegalArgumentException("用户不能为空！");
        }

        if (StringUtils.isBlank(user.getUsername())){
            map.put("usermsg","账号不能为空");
            return map;
        }

        if (StringUtils.isBlank(user.getPassword())){
            map.put("passwordmsg","密码不能为空");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())){
            map.put("Emailmsg","邮箱不能为空");
            return map;
        }

        //用用户名验证用户是否存在
        int i = userMapper.JudgeByName(user.getUsername());
        if (i != 0){
            map.put("usermsg","该用户已存在！！");
            return map;
        }

        //用邮箱验证用户是否存在
        int i1 = userMapper.JudgeByEmail(user.getEmail());
        if (i1 != 0){
            map.put("Emailmsg","该邮箱已注册！");
            return map;
        }
        user.setSalt(CommunityUtil.getUUID().substring(0,5));
        user.setPassword(CommunityUtil.MD5(user.getPassword()+user.getSalt()));
        user.setStatus(Constant.USER_NOT_ACTIVE);
        user.setType(Constant.USER_TYPE_USER);
        user.setActivationCode(CommunityUtil.getUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png",new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        userMapper.insertUser(user);
        Context context = new Context();
        context.setVariable("email",user.getEmail());
        String url = domain + contextpath + "/activation/" + user.getId()+"/" + user.getActivationCode();
        context.setVariable("url",url);
        String content = templateEngine.process("/mail/activation",context);
        mailClient.sendMail(user.getEmail(),"激活账号",content);
        return map;
    }
    @Override
    public int ActivationUser(int userId,String code){
        User user = userMapper.selectById(userId);
        if (user.getStatus() == Constant.USER_ACTIVE){
            return Constant.ACTIVATION_REPEAT;
        }else if (user.getActivationCode().equals(code)){
            userMapper.updateStatus(userId,Constant.USER_ACTIVE);
            return Constant.ACTIVATION_SUCCESS;
        }else {
            return Constant.ACTIVATION_FAILURE;
        }

    }

}
